{% extends 'base.html' %}
{% load static %}

{% block title %}游戏大厅{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <!-- 左侧面板 -->
        <div class="col-md-3">
            <div class="card">
                <div class="card-header">
                    <h5><i class="fas fa-user"></i> 玩家信息</h5>
                </div>
                <div class="card-body">
                    <div class="text-center mb-3">
                        <div class="avatar-placeholder bg-primary text-white rounded-circle d-inline-flex align-items-center justify-content-center" style="width: 80px; height: 80px;">
                            <i class="fas fa-user fa-2x"></i>
                        </div>
                        <h6 class="mt-2">{{ user.nickname|default:user.username }}</h6>
                    </div>
                    <div class="row text-center">
                        <div class="col-6">
                            <div class="border-end">
                                <h6 class="text-success">{{ user.wins|default:0 }}</h6>
                                <small class="text-muted">胜利</small>
                            </div>
                        </div>
                        <div class="col-6">
                            <h6 class="text-danger">{{ user.losses|default:0 }}</h6>
                            <small class="text-muted">失败</small>
                        </div>
                    </div>
                    <hr>
                    <div class="text-center">
                        <h6 class="text-warning">
                            <i class="fas fa-coins"></i> {{ user.coins|default:1000 }}
                        </h6>
                        <small class="text-muted">游戏币</small>
                    </div>
                </div>
            </div>

            <div class="card mt-3">
                <div class="card-header">
                    <h5><i class="fas fa-layer-group"></i> 我的卡组</h5>
                </div>
                <div class="card-body">
                    <div id="decksList">
                        <div class="text-center text-muted">
                            <i class="fas fa-spinner fa-spin"></i> 加载中...
                        </div>
                    </div>
                    <div class="d-grid mt-3">
                        <a href="{% url 'deck-builder' %}" class="btn btn-outline-primary btn-sm">
                            <i class="fas fa-plus"></i> 创建新卡组
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- 主游戏区域 -->
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h5><i class="fas fa-gamepad"></i> 游戏大厅</h5>
                </div>
                <div class="card-body">
                    <!-- 匹配区域 -->
                    <div class="matchmaking-queue text-center p-4 mb-4">
                        <h4><i class="fas fa-search"></i> 寻找对手</h4>
                        <p class="mb-3">选择一个卡组开始匹配</p>
                        
                        <div class="mb-3">
                            <select class="form-select" id="selectedDeck">
                                <option value="">请选择卡组...</option>
                            </select>
                        </div>
                        
                        <div class="d-grid gap-2 d-md-block">
                            <button class="btn btn-success btn-lg" id="startMatchmaking" disabled>
                                <i class="fas fa-play"></i> 开始匹配
                            </button>
                            <button class="btn btn-danger btn-lg" id="stopMatchmaking" style="display: none;">
                                <i class="fas fa-stop"></i> 取消匹配
                            </button>
                            <button class="btn btn-warning btn-lg" id="startAITest" disabled>
                                <i class="fas fa-robot"></i> 人机测试
                            </button>
                        </div>
                        
                        <div id="matchmakingStatus" class="mt-3" style="display: none;">
                            <div class="alert alert-info">
                                <i class="fas fa-spinner fa-spin"></i> 正在寻找对手...
                                <div class="mt-2">
                                    <small>等待时间: <span id="waitTime">0</span>秒</small><br>
                                    <small>匹配评分: <span id="matchmakingRating">0</span></small>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 游戏历史 -->
                    <div class="card">
                        <div class="card-header">
                            <h6><i class="fas fa-history"></i> 最近游戏</h6>
                        </div>
                        <div class="card-body">
                            <div id="recentGames">
                                <div class="text-center text-muted">
                                    <i class="fas fa-spinner fa-spin"></i> 加载中...
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 右侧面板 -->
        <div class="col-md-3">
            <div class="card">
                <div class="card-header">
                    <h5><i class="fas fa-trophy"></i> 排行榜</h5>
                </div>
                <div class="card-body">
                    <div id="leaderboard">
                        <div class="text-center text-muted">
                            <i class="fas fa-spinner fa-spin"></i> 加载中...
                        </div>
                    </div>
                </div>
            </div>

            <div class="card mt-3">
                <div class="card-header">
                    <h5><i class="fas fa-cog"></i> 快速操作</h5>
                </div>
                <div class="card-body">
                    <div class="d-grid gap-2">
                        <a href="{% url 'card-collection' %}" class="btn btn-outline-primary">
                            <i class="fas fa-gem"></i> 卡牌收藏
                        </a>
                        <a href="{% url 'deck-builder' %}" class="btn btn-outline-primary">
                            <i class="fas fa-layer-group"></i> 卡组构建
                        </a>
                        <button class="btn btn-outline-info" onclick="refreshData()">
                            <i class="fas fa-sync"></i> 刷新数据
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let matchmakingInterval = null;
let waitTimeInterval = null;
let waitTime = 0;

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    loadDecks();
    loadRecentGames();
    loadLeaderboard();
    
    // 绑定事件
    document.getElementById('selectedDeck').addEventListener('change', function() {
        const startBtn = document.getElementById('startMatchmaking');
        const aiTestBtn = document.getElementById('startAITest');
        const hasDeck = !!this.value;
        startBtn.disabled = !hasDeck;
        aiTestBtn.disabled = !hasDeck;
    });
    
    document.getElementById('startMatchmaking').addEventListener('click', startMatchmaking);
    document.getElementById('stopMatchmaking').addEventListener('click', stopMatchmaking);
    document.getElementById('startAITest').addEventListener('click', startAITest);
});

// 加载卡组列表
async function loadDecks() {
    try {
        const response = await fetch('/api/decks/');
        
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        const data = await response.json();
        const decks = Array.isArray(data) ? data : (data.results || []);
        
        const select = document.getElementById('selectedDeck');
        const decksList = document.getElementById('decksList');
        
        // 清空选项
        select.innerHTML = '<option value="">请选择卡组...</option>';
        decksList.innerHTML = '';
        
        if (decks.length === 0) {
            decksList.innerHTML = '<div class="text-center text-muted"><i class="fas fa-layer-group"></i><br>暂无卡组<br><small>请先创建卡组</small></div>';
            return;
        }
        
        // 添加选项
        decks.forEach(deck => {
            const option = document.createElement('option');
            option.value = deck.id;
            option.textContent = `${deck.name} (${deck.total_cards}张卡)`;
            select.appendChild(option);
        });
        
        // 显示卡组列表
        decks.forEach(deck => {
            const deckItem = document.createElement('div');
            deckItem.className = 'card mb-2';
            deckItem.innerHTML = `
                <div class="card-body py-2">
                    <h6 class="card-title mb-1">${deck.name}</h6>
                    <small class="text-muted">${deck.total_cards}张卡牌</small>
                </div>
            `;
            decksList.appendChild(deckItem);
        });
        
    } catch (error) {
        console.error('加载卡组失败:', error);
        const decksList = document.getElementById('decksList');
        if (decksList) {
            decksList.innerHTML = '<div class="text-center text-muted"><i class="fas fa-exclamation-triangle"></i><br>暂无卡组<br><small>请先创建卡组</small></div>';
        }
    }
}

// 开始匹配
async function startMatchmaking() {
    const deckId = document.getElementById('selectedDeck').value;
    if (!deckId) return;
    
    try {
        const response = await fetch('/api/matchmaking/join/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({ deck_id: parseInt(deckId) })
        });
        
        if (response.ok) {
            const data = await response.json();
            
            if (data.game_id) {
                // 匹配成功，跳转到游戏
                showMessage('匹配成功！', 'success');
                setTimeout(() => {
                    window.location.href = `/game/${data.game_id}/`;
                }, 1000);
            } else {
                // 进入匹配队列
                document.getElementById('startMatchmaking').style.display = 'none';
                document.getElementById('stopMatchmaking').style.display = 'inline-block';
                document.getElementById('matchmakingStatus').style.display = 'block';
                
                // 更新匹配信息
                if (data.matchmaking_rating) {
                    document.getElementById('matchmakingRating').textContent = data.matchmaking_rating;
                }
                
                // 重置等待时间
                waitTime = 0;
                document.getElementById('waitTime').textContent = waitTime;
                
                // 开始轮询匹配状态和计时
                matchmakingInterval = setInterval(checkMatchmakingStatus, 2000);
                waitTimeInterval = setInterval(updateWaitTime, 1000);
            }
        } else {
            const error = await response.json();
            showMessage('开始匹配失败：' + error.error, 'error');
        }
    } catch (error) {
        showMessage('开始匹配失败：网络错误', 'error');
    }
}

// 停止匹配
async function stopMatchmaking() {
    try {
        const response = await fetch('/api/matchmaking/leave/', {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCookie('csrftoken')
            }
        });
        
        if (response.ok) {
            document.getElementById('startMatchmaking').style.display = 'inline-block';
            document.getElementById('stopMatchmaking').style.display = 'none';
            document.getElementById('matchmakingStatus').style.display = 'none';
            
            if (matchmakingInterval) {
                clearInterval(matchmakingInterval);
                matchmakingInterval = null;
            }
            if (waitTimeInterval) {
                clearInterval(waitTimeInterval);
                waitTimeInterval = null;
            }
            
            showMessage('已取消匹配', 'info');
        }
    } catch (error) {
        showMessage('取消匹配失败：网络错误', 'error');
    }
}

// 检查匹配状态
async function checkMatchmakingStatus() {
    try {
        const response = await fetch('/api/matchmaking/status/');
        const data = await response.json();
        
        if (!data.in_queue) {
            // 不在队列中，检查是否被匹配到游戏
            if (data.matched_game) {
                // 被匹配到游戏，跳转到游戏界面
                showMessage('匹配成功！', 'success');
                setTimeout(() => {
                    window.location.href = `/game/${data.matched_game.game_id}/`;
                }, 1000);
                return;
            }
            
            // 停止轮询
            stopMatchmaking();
        } else {
            // 更新等待时间和匹配评分
            if (data.wait_time !== undefined) {
                waitTime = data.wait_time;
                document.getElementById('waitTime').textContent = waitTime;
            }
            if (data.matchmaking_rating !== undefined) {
                document.getElementById('matchmakingRating').textContent = data.matchmaking_rating;
            }
            
            // 同时检查匹配结果
            await checkMatchResult();
        }
    } catch (error) {
        console.error('检查匹配状态失败:', error);
    }
}

// 检查匹配结果
async function checkMatchResult() {
    try {
        const response = await fetch('/api/matchmaking/check-result/');
        const data = await response.json();
        
        if (data.matched) {
            // 被匹配到游戏，跳转到游戏界面
            showMessage('匹配成功！', 'success');
            setTimeout(() => {
                window.location.href = `/game/${data.game_id}/`;
            }, 1000);
        }
    } catch (error) {
        console.error('检查匹配结果失败:', error);
    }
}

// 更新等待时间
function updateWaitTime() {
    waitTime++;
    document.getElementById('waitTime').textContent = waitTime;
}

// 加载最近游戏
async function loadRecentGames() {
    try {
        const response = await fetch('/api/games/');
        
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        const data = await response.json();
        const games = Array.isArray(data) ? data : (data.results || []);
        
        const container = document.getElementById('recentGames');
        
        if (games.length === 0) {
            container.innerHTML = '<div class="text-center text-muted"><i class="fas fa-gamepad"></i><br>暂无游戏记录<br><small>开始你的第一场游戏吧！</small></div>';
            return;
        }
        
        container.innerHTML = '';
        games.slice(0, 5).forEach(game => {
            const gameItem = document.createElement('div');
            gameItem.className = 'card mb-2';
            
            // 根据游戏状态设置不同的样式
            let statusClass = 'warning';
            let statusText = game.status;
            
            if (game.status === 'finished') {
                statusClass = 'success';
                statusText = '已结束';
            } else if (game.status === 'playing') {
                statusClass = 'primary';
                statusText = '进行中';
            } else if (game.status === 'waiting') {
                statusClass = 'info';
                statusText = '等待中';
            }
            
            gameItem.innerHTML = `
                <div class="card-body py-2">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="card-title mb-1">游戏 #${game.id}</h6>
                            <small class="text-muted">${statusText}</small>
                        </div>
                        <span class="badge bg-${statusClass}">${statusText}</span>
                    </div>
                </div>
            `;
            container.appendChild(gameItem);
        });
        
    } catch (error) {
        console.error('加载游戏记录失败:', error);
        const container = document.getElementById('recentGames');
        if (container) {
            container.innerHTML = '<div class="text-center text-muted"><i class="fas fa-gamepad"></i><br>暂无游戏记录<br><small>开始你的第一场游戏吧！</small></div>';
        }
    }
}

// 加载排行榜
async function loadLeaderboard() {
    // 这里可以添加排行榜API
    document.getElementById('leaderboard').innerHTML = '<div class="text-center text-muted">排行榜功能开发中...</div>';
}

// 开始人机测试
async function startAITest() {
    const deckId = document.getElementById('selectedDeck').value;
    if (!deckId) return;
    
    try {
        const response = await fetch('/api/games/start_ai_game/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({ deck_id: parseInt(deckId) })
        });
        
        if (response.ok) {
            const data = await response.json();
            showMessage('人机测试开始！', 'success');
            setTimeout(() => {
                window.location.href = `/game/${data.game_id}/`;
            }, 1000);
        } else {
            const error = await response.json();
            showMessage('开始人机测试失败：' + error.error, 'error');
        }
    } catch (error) {
        showMessage('开始人机测试失败：网络错误', 'error');
    }
}

// 刷新数据
function refreshData() {
    loadDecks();
    loadRecentGames();
    loadLeaderboard();
    showMessage('数据已刷新', 'info');
}
</script>
{% endblock %}
